<template>
  <a-modal v-model:open="isShow" :title="title" @cancel="handleCancel">
    <input type="file" ref="file"/>
    <slot name="template"/>
    <div v-if="uploadMsg !== '' && type === 'commPost'" style="color:red;">导入结果：{{ uploadMsg }}</div>
    <template #footer>
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="upload" :loading="uploadLoading">上传</a-button>
    </template>
  </a-modal>
</template>
<script setup>
import { ref } from 'vue'
import {message} from "ant-design-vue";
import {importFile, postFile, commPost} from "@utils/service/index.js";
const isShow = ref(false)
const props = defineProps({
  url:{
    type:String,
    required:true
  },
  method:{
    type:String,
    default:'post'
  },
  name:{
    type:String,
    required:true
  },
  title:{
    type:String,
    default:'上传文件'
  },
  type:{
    type:String,
    default:'upload'
  }
})
const uploadMsg = ref('')
const file = ref({})
const uploadLoading = ref(false)
const handleCancel = () => {
  isShow.value = false
  file.value.value = ''
  uploadMsg.value = ''
}
const emit = defineEmits(['search'])
const handleShow = () => {
  isShow.value = true
}
const upload = async () => {
  try {
    uploadLoading.value = true
    const fileObj = file.value.files[0]
    if(file.value.files && file.value.files.length === 0){
      return message.error('请选择文件')
    }
    let formData = new FormData()
    formData.append('file', fileObj)
    if(props.type === 'upload') {
      let res = await postFile(props.url, props.method, formData, `${props.name}.xlsx`)
    }else if(props.type === 'import'){
      let res = await importFile(props.url, props.method, formData, `${props.name}.xlsx`)
    }else if(props.type === 'commPost') {
      let res = await commPost({ url: props.url, method: props.method, data: formData})
      uploadMsg.value = res.message
      message.success('上传成功')
    }
    handleCancel()
    emit('search')
  } catch (e) {
    message.error(e)
    uploadMsg.value = e
    file.value.value = ''
  } finally {
    uploadLoading.value = false
  }
}
defineExpose({
  handleShow
})
</script>
<style scoped>

</style>
